
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import DAO.DanhMucDAO;
import DAO.DonDatHangDAO;
import DAO.LoaiSanPhamDAO;
import DAO.SanPhamDAO;
import POJO.DanhMucPOJO;
import POJO.LoaiSanPhamPOJO;
import POJO.NguoiDungPOJO;
import POJO.SanPhamPOJO;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author NGUYEN CONG BINH
 */
@WebServlet(name = "ShoppingCartController", urlPatterns = {"/ShoppingCartController"})
public class ShoppingCartController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
          
        response.setContentType("text/html;charset=UTF-8");
//         PrintWriter out = response.getWriter();
        try {

            HttpSession session = request.getSession();

            //bảng danh muc
            ArrayList<DanhMucPOJO> dm = DanhMucDAO.layDanhSachDanhMuc();
            request.setAttribute("danhmucAttribute", dm);
            //bảng loại sản phẩm
            ArrayList<LoaiSanPhamPOJO> loaisanpham = LoaiSanPhamDAO.layDanhSachLoaiSanPham();
            request.setAttribute("loaisanphamAttribute", loaisanpham);
            //bảng sản phẩm
            ArrayList<SanPhamPOJO> sanpham = SanPhamDAO.layDanhSachSanPham();
            request.setAttribute("sanphamAttribute", sanpham);


            ArrayList<SanPhamPOJO> gioHang = null;

            if (session.getAttribute("GioHang") == null) {
                gioHang = new ArrayList<SanPhamPOJO>();
                session.setAttribute("GioHang", gioHang);
            } else {
                gioHang = (ArrayList<SanPhamPOJO>) session.getAttribute("GioHang");
            }

            String action = request.getParameter("Action");
            if (action != null) {


                if (action.equals("Buy")) {
                    int maSanPham = Integer.parseInt(request.getParameter("MaSanPham"));
                    boolean flag = false;
                    for (int i = 0; i < gioHang.size(); i++) {
                        SanPhamPOJO sp = gioHang.get(i);
                        if (sp.getMaSanPham() == maSanPham) {
                            sp.setSoLuong(sp.getSoLuong() + 1);
                            flag = true;
                            break;
                        }
                    }
                    if (flag == false) {
                        SanPhamPOJO g = SanPhamDAO.layChiTietSanPham(maSanPham);
                        g.setSoLuong(1);
                        //out.println(g.getSoLuong());
                        gioHang.add(g);
                    }
                    request.getRequestDispatcher("/ShoppingCart.jsp").forward(request, response);
                }
//                if (action.equals("Buy")) {
//                    int maSanPham = Integer.parseInt(request.getParameter("MaSanPham"));
//                    boolean flag = false;
//                    for (int i = 0; i < gioHang.size(); i++) {
//                        SanPhamPOJO sp = gioHang.get(i);
//                        if (maSanPham == gioHang.get(i).getMaSanPham()) {
//                            gioHang.get(i).setSoLuong(gioHang.get(i).getSoLuong() + 1);
//                            flag = true;
//                            break;
//                        }
//                    }
//                    if (flag == false) {
//                        SanPhamPOJO g = SanPhamDAO.layChiTietSanPham(maSanPham);
//                        g.setSoLuong(1);
//                        gioHang.add(g);
//                    }
//                    request.getRequestDispatcher("/ShoppingCart.jsp").forward(request, response);
//                }
                //DeleteItems
                if (action.equals("DeleteItem")) {
                    if (request.getParameterValues("MaSanPham") != null) {
                        String maXoa = request.getParameter("MaSanPham");
                        for (int j = 0; j < gioHang.size(); j++) {
                            SanPhamPOJO sp = gioHang.get(j);
                            if (sp.getMaSanPham() == Integer.parseInt(maXoa)) {
                                gioHang.remove(j);
                            }
                        }
                    } else {
                        request.setAttribute("Error", "Bạn chưa chọn sản phẩm cần xóa!");
                    }
                    request.getRequestDispatcher("/ShoppingCart.jsp").forward(request, response);
                }
                if (action.equals("DeleteAll")) {
                    session.removeAttribute("GioHang");
                    request.getRequestDispatcher("/ShoppingCart.jsp").forward(request, response);
                }
                if (action.equals("View")) {
                    request.getRequestDispatcher("/ShoppingCart.jsp").forward(request, response);
                }

            }
            if (request.getParameter("bt_luugiohang") != null) {
                try {
                    NguoiDungPOJO kh = new NguoiDungPOJO();
                    if (session.getAttribute("KhachHang") != null) {
                        kh = (NguoiDungPOJO) session.getAttribute("KhachHang");
                        int t = DonDatHangDAO.capNhatHoaDon2(kh, gioHang);
                        session.removeAttribute("GioHang");
                        if (t == 1) {
                            request.setAttribute("Error", "Cập nhật hóa đơn thành công!");
                        } else {
                            request.setAttribute("Error", "Cập nhật hóa đơn thất bại!");
                        }
                    } else {
                        request.setAttribute("Error", "Bạn chưa đăng nhập!");
                    }
                    request.getRequestDispatcher("/ShoppingCart_Succeed.jsp").forward(request, response);
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
            if (request.getParameter("bt_xoa") != null) {
                if (request.getParameterValues("chb_xoa") != null) {
                    String[] maXoa = request.getParameterValues("chb_xoa");
                    for (int i = 0; i < maXoa.length; i++) {
                        for (int j = 0; j < gioHang.size(); j++) {
                            SanPhamPOJO sp = gioHang.get(j);
                            if (sp.getMaSanPham() == Integer.parseInt(maXoa[i])) {
                                gioHang.remove(j);
                            }
                        }
                    }
                } else {
                    request.setAttribute("Error", "Bạn chưa chọn sản phẩm cần xóa!");
                }
                request.getRequestDispatcher("/ShoppingCart.jsp").forward(request, response);
            }
            if (request.getParameter("bt_capnhat") != null) {
                String[] DSSoLuong = request.getParameterValues("tb_soluong");
                for (int j = 0; j < gioHang.size(); j++) {
                    SanPhamPOJO g = gioHang.get(j);
                    g.setSoLuong(Integer.parseInt(DSSoLuong[j]));
                }
                request.getRequestDispatcher("/ShoppingCart.jsp").forward(request, response);
            }
        } finally {
            // out.close();
        }
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
       @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);


        } catch (SQLException ex) {
            Logger.getLogger(ShoppingCartController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);


        } catch (SQLException ex) {
            Logger.getLogger(ShoppingCartController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
